

#import "FAMMineAgeViewController.h"

@interface FAMMineAgeViewController ()
@property (weak, nonatomic) IBOutlet UIDatePicker *FAMDatePicker;
@property (nonatomic, assign)NSInteger FAMNowTime;
@property (nonatomic, strong)NSString *FAMAge;
@end

@implementation FAMMineAgeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.FAMDatePicker.maximumDate = [NSDate new];
    self.FAMNowTime = ([FAMTool FAM_getNowTimeTimestamp]).integerValue;
    NSDate *today = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:today];
    [components setYear:[components year] - 20];
    NSDate *twentyYearsAgoToday = [calendar dateFromComponents:components];
    [self.FAMDatePicker setDate:twentyYearsAgoToday];
    self.FAMAge = [FAMUserManger shareInstance].userModel.age;
}
- (IBAction)FAM_pickerValueChangedClick:(UIDatePicker *)sender {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateStyle = NSDateFormatterMediumStyle;
    dateFormatter.timeStyle = NSDateFormatterShortStyle;
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    dateFormatter.locale = [[NSLocale alloc]initWithLocaleIdentifier:@"Asia/Beijing"];
    NSString *dateString = [dateFormatter stringFromDate:sender.date];
    NSDate *tempDate = [dateFormatter dateFromString:dateString];
    NSInteger choseTime = [tempDate timeIntervalSince1970] * 1000;
    NSInteger age = (self.FAMNowTime - choseTime)/1000/3600/24/365;
    self.FAMAge = [NSString stringWithFormat:@"%ld",age];
}


- (IBAction)FAMSaveButtonClick:(UIButton *)sender {
    WeakSelf(self);
    [self showHudInKeyWindowWithHint:nil];
    [FAMHttpTool FAM_PutFoodmateUserdataWithParameters:[NSMutableDictionary dictionaryWithDictionary:@{@"data":@{@"age":self.FAMAge}}] success:^(FAMFoodmateUserdataModel * _Nonnull model, NSString * _Nonnull msg) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf hideHudKeyWindow];
            [FAMUserManger shareInstance].userModel.age = weakSelf.FAMAge;
            [weakSelf.navigationController popViewControllerAnimated:YES];
        });
    } failure:^(NSString * _Nonnull errorInfo) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf hideHudKeyWindow];
            [weakSelf showHint:errorInfo];
        });
    }];
}


@end
